/*
 * Copyright 2016-2021 chronicle.software
 *
 * https://chronicle.software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.openhft.chronicle.values;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import static net.openhft.chronicle.values.Nullability.NULLABLE;

/**
 * This class exists for DRY between {@link EnumFieldModel} and {@link CharSequenceFieldModel}.
 */
final class FieldNullability {

    final FieldModel model;
    /**
     * Default is {@link Nullability#NULLABLE}, but not set, to distinguish "not set explicitly
     * case"
     */
    Nullability nullability;

    FieldNullability(FieldModel model) {
        this.model = model;
    }

    Nullability nullability() {
        return nullability != null ? nullability : NULLABLE;
    }

    public void addInfo(Method m, MethodTemplate template) {
        Parameter annotatedParameter = template.annotatedParameter.apply(m);
        if (annotatedParameter == null)
            return;
        Nullability explicitNullability = Nullability.explicitNullability(annotatedParameter);
        if (explicitNullability != null) {
            if (nullability != null && nullability != explicitNullability) {
                throw new IllegalStateException("Conflicting explicit nullability in parameters " +
                        "of methods accessing field " + model.name);
            }
            nullability = explicitNullability;
        }
    }
}
